package org.openzip.jarsfx.unpacking.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

public class JarToFolderCopier
{
	public boolean copy(JarFile jarFrom, File dirTo) 
		throws IOException, FileNotFoundException{
		Enumeration entries = jarFrom.entries();
		while (entries.hasMoreElements()){
			ZipEntry entry = (ZipEntry)entries.nextElement();
			if(!entry.toString().startsWith("data")){
				continue;
			}
			System.out.println(entry.toString());

			InputStream inp = jarFrom.getInputStream(entry);

			String relPath = entry.toString();
			String cleanPath = relPath.substring(5); // 5 - "data/"
			this._copyfile(inp, dirTo.getAbsolutePath(), cleanPath);

		}

		return true;
	}

	private void _copyfile(InputStream in, String dtFile, String cleanPath) 
		throws IOException, FileNotFoundException{
			System.out.println("Clean path: " + cleanPath);
			boolean isDir = cleanPath.endsWith("/");
			String newPath = dtFile + File.separator + 
				cleanPath.replaceAll("/", File.separator.replaceAll("\\\\", "\\\\\\\\"));
			System.out.println("New path: " + newPath);

			File f2 = new File(newPath);
			//bez milosti přepisujeme
			/*if(f2.exists()){
				System.out.println("File already exists.");
				System.out.println("=========================");
				return;
			}*/
			
			if(isDir){
				boolean b = f2.mkdirs();
				System.out.println("Creating of the dir " + f2.getName() + (b ? " succeeded" : " failed") + ".");
			}
			else{
				f2.getParentFile().mkdirs();
				// For Append the file.
				// OutputStream out = new FileOutputStream(f2,true);

				// For Overwrite the file.
				OutputStream out = new FileOutputStream(f2);

				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0){
					out.write(buf, 0, len);
				}
				in.close();
				out.close();
			}

			System.out.println("=========================");
	}
}
